package com.qfedu.stussm.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.stussm.dao.StudentDao;
import com.qfedu.stussm.dto.StuDto;
import com.qfedu.stussm.entity.Student;
import com.qfedu.stussm.service.intf.StudentService;
import com.qfedu.stussm.vo.PageBeanVo;
import com.qfedu.stussm.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao dao;

    //增加
    @Override
    public int add(Student student) {
       return dao.add(student);
    }
    //查询
    @Override
    public List<PageBeanVo> selectAll() {
        return dao.selectAll();
    }

    @Override
    public PageBeanVo queryPage(String stu_name, int page, int limit) {
        //1.开启分
        PageHelper.startPage(page,limit);
        //2.PageInfo name="" name=null
        if(stu_name!=null && stu_name.length()>0){
            stu_name="%"+stu_name+"%";
        }else {
            stu_name=null;
        }
        PageInfo<StuDto> pageInfo=new PageInfo<>(dao.selectLikeAll(stu_name));
        //3.返回
        return new PageBeanVo(pageInfo.getTotal(),pageInfo.getList());
    }
    //修改
    @Override
    public R update(Student student) {
        if(dao.update(student)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }
    //删除
    @Override
    public R del(int id) {
        if(dao.del(id)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public void createExcel(HttpServletResponse response) throws IOException {
        //1.查询数据
        List<Student> list = dao.sel();
        //2.设置文件下载
        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename=department_"+System.currentTimeMillis()+".xlsx");
        //3.生成Excel并写出
        EasyExcel.write(response.getOutputStream(),Student.class).sheet(System.currentTimeMillis()+"").doWrite(list);
    }

    @Override
    public R uploadExcel(MultipartFile file) throws IOException {
        //1.获取上传的内容 2.解析文件 3.批量新增
        //1.验证上传文件是否非空
        if(!file.isEmpty()){
            //2.获取上传内容
            InputStream is=file.getInputStream();

            //3.解析Excel
            EasyExcel.read(is,Student.class,new PageReadListener<Student>((list)->{
                //4.调用 dao 实现批量新增
                dao.addBatch(list);
            })).sheet().doRead();
        }
        return R.ok();
    }

}
